package com.cmict.data.system.service.auth;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.anji.captcha.model.common.ResponseModel;
import com.anji.captcha.model.vo.CaptchaVO;
import com.anji.captcha.service.CaptchaService;
import com.cmict.data.framework.common.enums.CommonStatusEnum;
import com.cmict.data.framework.common.enums.ConfKeyEnum;
import com.cmict.data.framework.common.enums.UserTypeEnum;
import com.cmict.data.framework.common.util.collection.SetUtils;
import com.cmict.data.framework.common.util.monitor.TracerUtils;
import com.cmict.data.framework.common.util.servlet.ServletUtils;
import com.cmict.data.framework.security.core.util.RSAUtils;
import com.cmict.data.framework.tenant.core.context.TenantContextHolder;
import com.cmict.data.system.api.logger.dto.LoginLogCreateReqDTO;
import com.cmict.data.system.api.sms.SmsCodeApi;
import com.cmict.data.system.api.social.dto.SocialUserBindReqDTO;
import com.cmict.data.system.controller.admin.auth.vo.*;
import com.cmict.data.system.controller.admin.conf.vo.ConfSystem;
import com.cmict.data.system.controller.admin.oauth2.vo.token.OAuth2AccessTokenPageReqVO;
import com.cmict.data.system.convert.auth.AuthConvert;
import com.cmict.data.system.dal.dataobject.logger.LoginLogDO;
import com.cmict.data.system.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import com.cmict.data.system.dal.dataobject.permission.MenuDO;
import com.cmict.data.system.dal.dataobject.permission.RoleDO;
import com.cmict.data.system.dal.dataobject.permission.UserRoleDO;
import com.cmict.data.system.dal.dataobject.user.AdminUserDO;
import com.cmict.data.system.dal.mysql.permission.UserRoleMapper;
import com.cmict.data.system.dal.redis.auth.LoginLockRedisDAO;
import com.cmict.data.system.enums.auth.OAuth2ClientConstants;
import com.cmict.data.system.enums.logger.LoginLogTypeEnum;
import com.cmict.data.system.enums.logger.LoginResultEnum;
import com.cmict.data.system.enums.login.LoginTypeEnum;
import com.cmict.data.system.enums.permission.MenuTypeEnum;
import com.cmict.data.system.enums.sms.SmsSceneEnum;
import com.cmict.data.system.service.conf.ConfService;
import com.cmict.data.system.service.logger.LoginLogService;
import com.cmict.data.system.service.member.MemberService;
import com.cmict.data.system.service.oauth2.OAuth2TokenService;
import com.cmict.data.system.service.permission.PermissionService;
import com.cmict.data.system.service.permission.RoleService;
import com.cmict.data.system.service.social.SocialUserService;
import com.cmict.data.system.service.user.AdminUserService;
import com.cmict.data.system.util.ip.BDIPUtils;
import com.cmict.data.system.controller.admin.auth.vo.*;
import com.google.common.annotations.VisibleForTesting;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.util.*;

import static com.cmict.data.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cmict.data.framework.common.util.collection.CollectionUtils.convertSet;
import static com.cmict.data.framework.common.util.servlet.ServletUtils.getClientIP;
import static com.cmict.data.framework.web.core.util.WebFrameworkUtils.getLoginUserId;
import static java.util.Collections.singleton;
import static com.cmict.data.system.enums.ErrorCodeConstants.*;

/**
 * Auth Service 实现类
 *
 * @author awesome
 */
@Service
@Slf4j
public class AdminAuthServiceImpl implements AdminAuthService {

    @Resource
    private AdminUserService userService;
    @Resource
    @Lazy // 延迟加载，因为存在相互依赖的问题
    private AuthenticationManager authenticationManager;
    @Resource
    private CaptchaService captchaService;
    @Resource
    private PermissionService permissionService;
    @Resource
    private LoginLogService loginLogService;
    //    @Resource
//    private UserSessionService userSessionService;
    @Resource
    private OAuth2TokenService oauth2TokenService;

    @Resource
    private SocialUserService socialUserService;
    @Resource
    private LoginLockRedisDAO loginLockRedisDAO;
    @Resource
    private ConfService confService;
    @Resource
    private MemberService memberService;

    @Resource
    private OAuth2TokenService oAuth2TokenService;

    @Resource
    private Validator validator;

    @Resource
    private SmsCodeApi smsCodeApi;

    @Resource
    private UserRoleMapper userRoleMapper;
    @Override
    public AdminUserDO authenticate(String username, String password) {
        ConfSystem conf = confService.getConfValueByConfKey(ConfKeyEnum.SYSTEM_SAFE.getConfKey());
        int passwordErrorNumber = Integer.valueOf(conf.getPasswordErrorNumber()); //错误次数  3 以下 不启动该功能
        String lockOrDelay = conf.getLockOrDelay();  //  //0 账号锁定  1 延时登录
        String delayTime = conf.getDelayTime(); //延迟时间

        String clientIP = getClientIP();
        String tenantId = TenantContextHolder.getTenantId().toString();
        final LoginLogTypeEnum logTypeEnum = LoginLogTypeEnum.LOGIN_USERNAME;
        // 校验账号是否存在
        AdminUserDO user = userService.getUserByUsername(username);
        if (user == null) {
            createLoginLog(null, username, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            throw exception(AUTH_LOGIN_BAD_USERNAME);
        }
        if (!userService.isPasswordMatch(password, user.getPassword())) {
            // admin 用户 只有自己可以修改,并且不可以禁用
            if ( ! username.equals("admin") ) {
                //登录延迟判断
                if(StringUtils.isEmpty(loginLockRedisDAO.get(tenantId,username ,clientIP))){
                    loginLockRedisDAO.set(tenantId,username ,clientIP,1);
                }else{
                    int num = Integer.valueOf(loginLockRedisDAO.get(tenantId,username ,clientIP));
                    num= num +1;
                    if(num >= passwordErrorNumber ){
                        loginLockRedisDAO.set(tenantId,username ,clientIP,num);
                        if(lockOrDelay.equals("1")){
                            throw exception(AUTH_LOGIN_BAD_LOCK,passwordErrorNumber,delayTime);
                        }else {
                            userService.updateUserStatus(user.getId(), CommonStatusEnum.DISABLE.getStatus());
                            user.setStatus(CommonStatusEnum.DISABLE.getStatus());
                            throw exception(AUTH_LOGIN_BAD_LOCK_DISABLED,passwordErrorNumber);
                        }
                    }
                    loginLockRedisDAO.set(tenantId,username ,clientIP,num);
                }
            }
            createLoginLog(user.getId(), username, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            throw exception(AUTH_LOGIN_BAD_CREDENTIALS);
        }
        // 校验是否禁用
        if (ObjectUtil.notEqual(user.getStatus(), CommonStatusEnum.ENABLE.getStatus())) {
            createLoginLog(user.getId(), username, logTypeEnum, LoginResultEnum.USER_DISABLED);
            throw exception(AUTH_LOGIN_USER_DISABLED);
        }
        if(passwordErrorNumber >=3 && lockOrDelay.equals("1")){
            //登录延迟
            if(StringUtils.isNotBlank(loginLockRedisDAO.get(tenantId,username ,clientIP) )){
                int num = Integer.valueOf(loginLockRedisDAO.get(tenantId,username ,clientIP));
                if(num >= passwordErrorNumber ){
                    throw exception(AUTH_LOGIN_BAD_LOCK,passwordErrorNumber,delayTime);
                }else{
                    loginLockRedisDAO.delete(tenantId,username ,clientIP);
                }

            }
        }
        return user;
    }

    @Override
    public AuthLoginRespVO login(AuthLoginReqVO reqVO) {
        userService.checkUserNameRegexp(reqVO.getUsername());
        // 判断验证码是否正确
        verifyCaptcha(reqVO);
        String password = RSAUtils.decrypt(reqVO.getPassword());
        // 使用账号密码，进行登录
        AdminUserDO user = authenticate(reqVO.getUsername(), password);

        // 如果 socialType 非空，说明需要绑定社交用户
        if (reqVO.getSocialType() != null) {
            socialUserService.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(),
                    reqVO.getSocialType(), reqVO.getSocialCode(), reqVO.getSocialState()));
        }

        LoginLogDO loginLogDO = loginLogService.getNewLoginLogOne(reqVO.getUsername());
        ConfSystem conf= confService.getConfValueByConfKey(ConfKeyEnum.SYSTEM_SAFE.getConfKey());
        // 0  同时登录  1 单一登录     为1 时进行判断
        if(conf.getLoginMethod().equals("1")){
            OAuth2AccessTokenPageReqVO OreqVO = new OAuth2AccessTokenPageReqVO();
            OreqVO.setUserId(user.getId());
            OreqVO.setLoginType(LoginTypeEnum.LOGIN_USERNAME.getType());
            List<OAuth2AccessTokenDO>   oAuth2AccessTokenDOS =    oAuth2TokenService.getAccessTokenList(OreqVO);
            // 0 后登陆提出先登录   1  已登录禁止再登录
            if(conf.getLoginOrder().equals("0")){
                if(oAuth2AccessTokenDOS!= null && oAuth2AccessTokenDOS.size()>0){
                    for (OAuth2AccessTokenDO oAuth2AccessTokenDO : oAuth2AccessTokenDOS) {
                        oAuth2TokenService.removeAccessToken(oAuth2AccessTokenDO.getAccessToken());
                    }
                }

            }else{
                if(oAuth2AccessTokenDOS!= null && oAuth2AccessTokenDOS.size()>0){
                    throw exception(AUTH_LOGIN_ORDER);
                }

            }
        }
        // 创建 Token 令牌，记录登录日志
        AuthLoginRespVO tokenAfterLoginSuccess = createTokenAfterLoginSuccess(user.getId(), reqVO.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME);

        tokenAfterLoginSuccess.setLoginTimeOutPeriod(conf.getLoginTimeOutPeriod()); //超时时间

        if(! conf.getOpenLoginPrompt()){
            return tokenAfterLoginSuccess;
        }
        //登录提示语
        Map<String, Object> map = new HashMap<>();
        if(loginLogDO != null){
            //登录提示语
            map.put("createTime",loginLogDO.getCreateTime());
            map.put("ip",loginLogDO.getUserIp());
            map.put("site",StringUtils.isBlank(loginLogDO.getSite()) ? "陕西省西安市" : loginLogDO.getSite() );
        }


        return  tokenAfterLoginSuccess.setLoginPrompt(map);
    }
    @Override
    public AuthLoginRespVO miniLogin(AuthLoginReqVO reqVO) {
        // 判断验证码是否正确
        verifyCaptcha(reqVO);
        String password = RSAUtils.decrypt(reqVO.getPassword());
        // 使用账号密码，进行登录
        AdminUserDO user = authenticate(reqVO.getUsername(), password);

        // 如果 socialType 非空，说明需要绑定社交用户
        if (reqVO.getSocialType() != null) {
            socialUserService.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(),
                    reqVO.getSocialType(), reqVO.getSocialCode(), reqVO.getSocialState()));
        }

        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user.getId(), reqVO.getUsername(), LoginLogTypeEnum.LOGIN_MINI);
    }

    @Override
    public void sendSmsCode(AuthSmsSendReqVO reqVO) {
        // 登录场景，验证是否存在
        if (userService.getUserByMobile(reqVO.getMobile()) == null) {
            throw exception(AUTH_MOBILE_NOT_EXISTS);
        }
        // 发送验证码
        smsCodeApi.sendSmsCode(AuthConvert.INSTANCE.convert(reqVO).setCreateIp(getClientIP()));
    }

    @Override
    public AuthLoginRespVO smsLogin(AuthSmsLoginReqVO reqVO) {
        // 校验验证码
        smsCodeApi.useSmsCode(AuthConvert.INSTANCE.convert(reqVO, SmsSceneEnum.ADMIN_MEMBER_LOGIN.getScene(), getClientIP()));

        // 获得用户信息
        AdminUserDO user = userService.getUserByMobile(reqVO.getMobile());
        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }

        // 缓存登陆用户到 Redis 中，返回 sessionId 编号
        return createTokenAfterLoginSuccess(user.getId(), reqVO.getMobile(), LoginLogTypeEnum.LOGIN_MOBILE);
    }

    @VisibleForTesting
    void verifyCaptcha(AuthLoginReqVO reqVO) {
        ConfSystem conf = confService.getConfValueByConfKey(ConfKeyEnum.SYSTEM_SAFE.getConfKey());

        // 如果验证码关闭，则不进行校验
        if (!conf.getOpenVerificationCode()) {
            return;
        }
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setCaptchaVerification(reqVO.getCode());
//            captchaVO.setCaptchaType("blockPuzzle");
        ResponseModel response = captchaService.verification(captchaVO);
        if (!response.isSuccess()) {
            throw exception(AUTH_LOGIN_CAPTCHA_CODE_ERROR);
        }
    }

    private void createLoginLog(Long userId, String username,
                                LoginLogTypeEnum logTypeEnum, LoginResultEnum loginResult) {
        // 插入登录日志
        LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
        reqDTO.setLogType(logTypeEnum.getType());
        reqDTO.setTraceId(TracerUtils.getTraceId());
        reqDTO.setUserId(userId);
        reqDTO.setUserType(getUserType().getValue());
        reqDTO.setUsername(username);
        reqDTO.setUserAgent(ServletUtils.getUserAgent());
        reqDTO.setUserIp(getClientIP());
        reqDTO.setResult(loginResult.getResult());
        try {
            ConfSystem conf = confService.getConfValueByConfKey(ConfKeyEnum.SYSTEM_SAFE.getConfKey());
            if(conf.getOpenLoginPrompt()!= null && conf.getOpenLoginPrompt()){
                BDIPUtils bdipUtils = new BDIPUtils();
                JSONObject jsonObject = bdipUtils.getDate(reqDTO.getUserIp());
                log.info("result={}", jsonObject.toJSONString());
                if (jsonObject != null) {
                    JSONObject json = jsonObject.getJSONObject("content");
                    log.info("地址={}", json.get("address"));
                    reqDTO.setSite(json.get("address").toString());
//                JSONObject pointJSON = json.getJSONObject("point");
//                log.info("经度={}; 纬度={}", pointJSON.get("x"), pointJSON.get("y"));
                }
            }
        }catch (Exception e){
//            e.printStackTrace();
            reqDTO.setSite("陕西省西安市");
        }finally {
            loginLogService.createLoginLog(reqDTO);
            // 更新最后登录时间
            if (userId != null && Objects.equals(LoginResultEnum.SUCCESS.getResult(), loginResult.getResult())) {
                userService.updateUserLogin(userId, getClientIP());
            }
        }
    }

    @Override
    public AuthLoginRespVO socialLogin(AuthSocialLoginReqVO reqVO) {
        // 使用 code 授权码，进行登录。然后，获得到绑定的用户编号
        Long userId = socialUserService.getBindUserId(UserTypeEnum.ADMIN.getValue(), reqVO.getType(),
                reqVO.getCode(), reqVO.getState());
        if (userId == null) {
            throw exception(AUTH_THIRD_LOGIN_NOT_BIND);
        }

        // 获得用户
        AdminUserDO user = userService.getUser(userId);
        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }

        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user.getId(), user.getUsername(), LoginLogTypeEnum.LOGIN_SOCIAL);
    }

    @Override
    public AuthLoginRespVO refreshToken(String refreshToken) {
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.refreshAccessToken(refreshToken, OAuth2ClientConstants.CLIENT_ID_DEFAULT);
        return AuthConvert.INSTANCE.convert(accessTokenDO);
    }
    private AuthLoginRespVO createTokenAfterLoginSuccess(Long userId, String username, LoginLogTypeEnum logType) {
        // 插入登陆日志
        createLoginLog(userId, username, logType, LoginResultEnum.SUCCESS);
        // 创建访问令牌
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.createAccessToken(userId, getUserType().getValue(),
                OAuth2ClientConstants.CLIENT_ID_DEFAULT, logType.getType(),null);
        // 构建返回结果
        return AuthConvert.INSTANCE.convert(accessTokenDO);
    }
    @Override
    public AuthMenuRespVO getHomePage() {
        // 获得角色列表
        Set<Long> roleIds = convertSet(userRoleMapper.selectListByUserId(getLoginUserId()),
                UserRoleDO::getRoleId);
//        Set<Long> roleIds = permissionService.getUserRoleIdsFromCache(getLoginUserId(), singleton(CommonStatusEnum.ENABLE.getStatus()));
        // 获得用户拥有的菜单列表
        List<MenuDO> menuList = permissionService.getRoleMenuListFromCache(roleIds,
                SetUtils.asSet(MenuTypeEnum.DIR.getType(), MenuTypeEnum.MENU.getType()), // 只要目录和菜单类型
                singleton(CommonStatusEnum.ENABLE.getStatus())); // 只要开启的
        List<AuthMenuRespVO> authMenuRespVOS = AuthConvert.INSTANCE.buildMenuTree(menuList);
        AuthMenuRespVO resultMenu = new AuthMenuRespVO();

        for (AuthMenuRespVO authMenuRespVO : authMenuRespVOS) {
            if(authMenuRespVO.getType() == 2 && StringUtils.isNoneBlank(authMenuRespVO.getComponent() )){
                return authMenuRespVO;

            }else{
                if(authMenuRespVO.getChildren() != null && authMenuRespVO.getChildren().size()>0){
                    return       getHomeMenuChildren(authMenuRespVO.getChildren(),authMenuRespVO.getPath());
                }
            }
        }
        throw exception(AUTH_FILE_LOGIN_NOT_MENU);
    }

    private AuthMenuRespVO getHomeMenuChildren(List<AuthMenuRespVO> authMenuRespVOS,String path) {
        for (AuthMenuRespVO authMenuRespVO : authMenuRespVOS) {
            if(authMenuRespVO.getType() == 2 && StringUtils.isNoneBlank(authMenuRespVO.getComponent() )){
                authMenuRespVO.setPath( path +"/" +authMenuRespVO.getPath());
                return authMenuRespVO;

            }else{
                if(authMenuRespVO.getChildren() != null && authMenuRespVO.getChildren().size()>0){
                    return    getHomeMenuChildren(authMenuRespVO.getChildren(), path +"/" + authMenuRespVO.getPath());
                }
            }
        }
        return null;
    }

//    private String createUserSessionAfterLoginSuccess(LoginUser loginUser, LoginLogTypeEnum logType, String userIp, String userAgent) {
//        // 插入登陆日志
//        createLoginLog(loginUser.getUsername(), logType, LoginResultEnum.SUCCESS);
//        // 缓存登录用户到 Redis 中，返回 Token 令牌
//        return userSessionService.createUserSession(loginUser, userIp, userAgent);
//    }

    @Override
    public void logout(String token, Integer logType) {
        // 删除访问令牌
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.removeAccessToken(token);
        if (accessTokenDO == null) {
            return;
        }
        // 删除成功，则记录登出日志
        createLogoutLog(accessTokenDO.getUserId(), accessTokenDO.getUserType(), logType);
    }

    private void createLogoutLog(Long userId, Integer userType, Integer logType) {
        LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
        reqDTO.setLogType(logType);
        reqDTO.setTraceId(TracerUtils.getTraceId());
        reqDTO.setUserId(userId);
        reqDTO.setUserType(userType);
        if (ObjectUtil.equal(getUserType().getValue(), userType)) {
            reqDTO.setUsername(getUsername(userId));
        } else {
            reqDTO.setUsername(memberService.getMemberUserMobile(userId));
        }
        reqDTO.setUserAgent(ServletUtils.getUserAgent());
        reqDTO.setUserIp(getClientIP());
        reqDTO.setResult(LoginResultEnum.SUCCESS.getResult());
        loginLogService.createLoginLog(reqDTO);
    }

    private String getUsername(Long userId) {
        if (userId == null) {
            return null;
        }
        AdminUserDO user = userService.getUser(userId);
        return user != null ? user.getUsername() : null;
    }

    private UserTypeEnum getUserType() {
        return UserTypeEnum.ADMIN;
    }


}
